package com.csii.modules.online.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.csii.core.api.Result;
import com.csii.core.util.oConvertUtils;
import com.csii.modules.online.auth.entity.OnlAuthData;
import com.csii.modules.online.auth.entity.OnlAuthPage;
import com.csii.modules.online.auth.entity.OnlAuthRelation;
import com.csii.modules.online.auth.service.IOnlAuthDataService;
import com.csii.modules.online.auth.service.IOnlAuthPageService;
import com.csii.modules.online.auth.service.IOnlAuthRelationService;
import com.csii.modules.online.auth.vo.AuthColumnVO;
import com.csii.modules.online.auth.vo.AuthPageVO;
import com.csii.modules.online.cgform.entity.OnlCgformButton;
import com.csii.modules.online.cgform.entity.OnlCgformField;
import com.csii.modules.online.cgform.service.IOnlCgformButtonService;
import com.csii.modules.online.cgform.service.IOnlCgformFieldService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description: cgform：表单权限操作
 * @Author: power-stdio
 * @Date: 2019-01-02
 * @Version: V1.0
 */
@RestController("onlCgformAuthController")
@RequestMapping({"/online/cgform/api"})
public class CgformAuthController {
	private static final Logger log = LoggerFactory.getLogger(CgformAuthController.class);
	@Autowired
	private IOnlCgformFieldService onlCgformFieldService;
	@Autowired
	private IOnlAuthDataService onlAuthDataService;
	@Autowired
	private IOnlAuthPageService onlAuthPageService;
	@Autowired
	private IOnlCgformButtonService onlCgformButtonService;
	@Autowired
	private IOnlAuthRelationService onlAuthRelationService;

	/**
	 * 根据cgformId查询OnlAuthData列表
	 *
	 * @param cgformId
	 * @return
	 */
	@GetMapping({"/authData/{cgformId}"})
	public Result<List<OnlAuthData>> authData(@PathVariable("cgformId") String cgformId) {

		Result result = new Result();
		//mybatis-plus的LambdaQueryWrapper
		LambdaQueryWrapper<OnlAuthData> wrapper = new LambdaQueryWrapper();
		wrapper.eq(OnlAuthData::getCgformId, cgformId);
		List list = this.onlAuthDataService.list(wrapper);
		result.setResult(list);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 在线生成表单-添加
	 *
	 * @param data .
	 * @return Result
	 */
	@PostMapping({"/authData"})
	public Result<OnlAuthData> authDataSave(@RequestBody OnlAuthData data) {
		Result result = new Result();

		try {
			this.onlAuthDataService.save(data);
			result.success("添加成功！");
		} catch (Exception var4) {
			log.error(var4.getMessage(), var4);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	 * 修改
	 *
	 * @param data
	 * @return
	 */
	@PutMapping({"/authData"})
	public Result<OnlAuthData> authData(@RequestBody OnlAuthData data) {
		Result result = new Result();
		this.onlAuthDataService.updateById(data);
		return result;
	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping({"/authData/{id}"})
	public Result<?> authDataByID(@PathVariable("id") String id) {
		this.onlAuthDataService.deleteOne(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 根据cgformId查询，并封装以map形式返回
	 *
	 * @param cgformId 表单id
	 * @return
	 */
	@GetMapping({"/authButton/{cgformId}"})
	public Result<Map<String, Object>> authButton(@PathVariable("cgformId") String cgformId) {
		Result result = new Result();
		LambdaQueryWrapper<OnlCgformButton> onlCgformButtonwrapper = Wrappers.lambdaQuery(OnlCgformButton.class).eq(OnlCgformButton::getCgformHeadId, cgformId)
				.eq(OnlCgformButton::getButtonStatus, 1)
				.select(OnlCgformButton::getButtonCode, OnlCgformButton::getButtonName, OnlCgformButton::getButtonStyle);
		List list1 = this.onlCgformButtonService.list(onlCgformButtonwrapper);
		LambdaQueryWrapper<OnlAuthPage> onlAuthPageWrapper = Wrappers.lambdaQuery(OnlAuthPage.class).eq(OnlAuthPage::getCgformId, cgformId).eq(OnlAuthPage::getType, 2);
		List list2 = this.onlAuthPageService.list(onlAuthPageWrapper);
		HashMap map = new HashMap();
		map.put("buttonList", list1);
		map.put("authList", list2);
		result.setResult(map);
		result.setSuccess(true);
		return result;
	}

	/**
	 * 先查询后修改
	 *
	 * @param onlAuthPage .
	 * @return Result
	 */
	@PostMapping({"/authButton"})
	public Result<OnlAuthPage> authButton(@RequestBody OnlAuthPage onlAuthPage) {
		Result result = new Result();

		try {
			String pageId = onlAuthPage.getId();
			boolean boo = false;
			if (oConvertUtils.isNotEmpty(pageId)) {
				OnlAuthPage page = (OnlAuthPage) this.onlAuthPageService.getById(pageId);
				if (page != null) {
					boo = true;
					page.setType(1); //1字段 2按钮
					this.onlAuthPageService.updateById(page);
				}
			}

			if (!boo) {
				onlAuthPage.setType(1);
				this.onlAuthPageService.save(onlAuthPage);
			}

			result.setResult(onlAuthPage);
			result.success("操作成功！");
		} catch (Exception var6) {
			log.error(var6.getMessage(), var6);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	 * 修改
	 *
	 * @param id id
	 * @return Result
	 */
	@PutMapping({"/authButton/{id}"})
	public Result<?> authButtonByid(@PathVariable("id") String id) {
		LambdaUpdateWrapper wrapper = Wrappers.lambdaUpdate(OnlAuthPage.class).eq(OnlAuthPage::getId, id).set(OnlAuthPage::getStatus, 0);
		this.onlAuthPageService.update(wrapper);
		return Result.ok("操作成功");
	}

	/**
	 * @param cgformId
	 * @return
	 */
	@GetMapping({"/authColumn/{cgformId}"})
	public Result<List<AuthColumnVO>> authColumn(@PathVariable("cgformId") String cgformId) {
		Result result = new Result();
		LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper();
		lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, cgformId);
		lambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
		List list = this.onlCgformFieldService.list(lambdaQueryWrapper);
		if (list == null || list.size() == 0) {
			return Result.error("未找到对应字段信息!");
		}

		LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(OnlAuthPage.class).eq(OnlAuthPage::getCgformId, cgformId).eq(OnlAuthPage::getType, 1);
		List list2 = this.onlAuthPageService.list(wrapper);
		ArrayList reslist = new ArrayList();
		Iterator iter = list.iterator();

		while (iter.hasNext()) {
			OnlCgformField field = (OnlCgformField) iter.next();
			AuthColumnVO authColumn = new AuthColumnVO(field);
			Integer status = 0;
			boolean listshow = false;
			boolean formshow = false;
			boolean editable = false;

			for (int var15 = 0; var15 < list2.size(); ++var15) {
				OnlAuthPage onlAuthPage = (OnlAuthPage) list2.get(var15);
				if (field.getDbFieldName().equals(onlAuthPage.getCode())) {
					status = onlAuthPage.getStatus();
					if (onlAuthPage.getPage() == 3 && onlAuthPage.getControl() == 5) {
						listshow = true;
					}

					if (onlAuthPage.getPage() == 5) {
						if (onlAuthPage.getControl() == 5) {
							formshow = true;
						} else if (onlAuthPage.getControl() == 3) {
							editable = true;
						}
					}
				}
			}

			authColumn.setStatus(status);
			authColumn.setListShow(listshow);
			authColumn.setFormShow(formshow);
			authColumn.setFormEditable(editable);
			reslist.add(authColumn);
		}

		result.setResult(reslist);
		Result.ok("加载字段权限数据完成");
		return result;
	}

	/**
	 * authColumn
	 *
	 * @param vo .
	 * @return Result
	 */
	@PutMapping({"/authColumn"})
	public Result<?> authColumnCheck(@RequestBody AuthColumnVO vo) {
		Result result = new Result();

		try {
			if (vo.getStatus() == 1) {
				this.onlAuthPageService.enableAuthColumn(vo);
			} else {
				this.onlAuthPageService.disableAuthColumn(vo);
			}

			result.success("操作成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	 * authColumn
	 *
	 * @param vo
	 * @return
	 */
	@PostMapping({"/authColumn"})
	public Result<?> authColumn(@RequestBody AuthColumnVO vo) {
		Result result = new Result();

		try {
			this.onlAuthPageService.switchAuthColumn(vo);
			result.success("操作成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}

		return result;
	}

	/**
	 * 表单权限列表
	 *
	 * @param cgformId .
	 * @param type .
	 * @return Result
	 */
	@GetMapping({"/authPage/{cgformId}/{type}"})
	public Result<List<AuthPageVO>> authPage(@PathVariable("cgformId") String cgformId, @PathVariable("type") Integer type) {
		Result result = new Result();
		List list = this.onlAuthPageService.queryAuthByFormId(cgformId, type);
		result.setResult(list);
		result.setSuccess(true);
		return result;
	}

	/**
	 * validAuthData
	 *
	 * @param cgformId .
	 * @return result
	 */
	@GetMapping({"/validAuthData/{cgformId}"})
	public Result<List<OnlAuthData>> validAuthData(@PathVariable("cgformId") String cgformId) {
		Result result = new Result();
		LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(OnlAuthData.class).eq(OnlAuthData::getCgformId, cgformId).eq(OnlAuthData::getStatus, 1)
				.select(OnlAuthData::getId, OnlAuthData::getRuleName);
		List list = this.onlAuthDataService.list(wrapper);
		result.setResult(list);
		result.setSuccess(true);
		return result;
	}

	/**
	 * @param roleId
	 * @param cgformId
	 * @param type
	 * @return
	 */
	@GetMapping({"/roleAuth"})
	public Result<List<OnlAuthRelation>> roleAuth(@RequestParam("roleId") String roleId, @RequestParam("cgformId") String cgformId, @RequestParam("type") Integer type) {
		Result result = new Result();
		LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(OnlAuthRelation.class).eq(OnlAuthRelation::getRoleId, roleId).eq(OnlAuthRelation::getCgformId, cgformId)
				.eq(OnlAuthRelation::getType, type).select(OnlAuthRelation::getAuthId);
		List list = this.onlAuthRelationService.list(wrapper);
		result.setResult(list);
		result.setSuccess(true);
		return result;
	}

	/**
	 *
	 * @param roleId
	 * @param cgformId
	 * @param jsonObject
	 * @return
	 */
	@PostMapping({"/roleColumnAuth/{roleId}/{cgformId}"})
	public Result<?> roleColumnAuth(@PathVariable("roleId") String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject) {
		Result result = new Result();
		JSONArray jsonArray = jsonObject.getJSONArray("authId");
		List stringList = jsonArray.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId, cgformId, 1, stringList);
		result.setSuccess(true);
		return result;
	}

	/**
	 * roleId
	 * @param roleId
	 * @param cgformId
	 * @param jsonObject
	 * @return
	 */
	@PostMapping({"/roleButtonAuth/{roleId}/{cgformId}"})
	public Result<?> roleButtonAuth(@PathVariable("roleId") String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject) {
		Result result = new Result();
		JSONArray jsonArray = jsonObject.getJSONArray("authId");
		List list = jsonArray.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId, cgformId, 2, list); //2是
		result.setSuccess(true);
		return result;
	}

	/**
	 * roleDataAuth：根据权限和表单id
	 *
	 * @param roleId     .
	 * @param cgformId   .
	 * @param jsonObject
	 * @return Result
	 */
	@PostMapping({"/roleDataAuth/{roleId}/{cgformId}"})
	public Result<?> roleDataAuth(@PathVariable("roleId") String roleId, @PathVariable("cgformId") String cgformId, @RequestBody JSONObject jsonObject) {
		Result result = new Result();
		JSONArray jsonArray = jsonObject.getJSONArray("authId");
		List stringList = jsonArray.toJavaList(String.class);
		this.onlAuthRelationService.saveRoleAuth(roleId, cgformId, 3, stringList);
		result.setSuccess(true);
		return result;
	}
}